package zyh.listener;

import zyh.servlet.DbDao;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
//@WebListener
public class ReqListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest req=(HttpServletRequest)sre.getServletRequest();
        HttpSession session=req.getSession();
        String sessionId=session.getId();
        String ip=req.getRemoteAddr();
        String page=req.getRequestURI();
        String user=(String)session.getAttribute("user");
        user = (user==null) ?"游客" :user;
        try {
            DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/1613580003",
                    "root", "123456");
            ResultSet rs = dd.query("select * from online_inf where session_id = ?", true, sessionId);
            if(rs.next())
            {
                rs.updateString(4,page);
                rs.updateLong(5,System.currentTimeMillis());
                rs.updateRow();
                rs.close();
            }
            else
                {
                    dd.insert("insert into online_inf values(?,?,?,?,?)",sessionId,user,ip,page,System.currentTimeMillis());
                }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre) {

    }
}
